
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Spinning.Spinning.Unitity;
using Spinning.Spinning.Interface;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input.Touch;

namespace Spinning.Spinning.Entity
{
    class ButtonSprite : Sprite, ITouchable
    {
        public string pressTestureName = "";
        protected Texture2D _pressTexture;
        public delegate void TouchEventHandler(BaseEntity entity, TouchLocation touchLocation);
        public TouchEventHandler OnTouchEvent, OnReleaseEvent, OnHoldEvent;
        bool _pressed;

        Texture2D Texture
        {
            get
            {
                if (_pressed&&_pressTexture!=null) 
                    return _pressTexture;
                else return _texture;
            }
        }

        public ButtonSprite():base() {
            _pressed = false;
            Static = false;
        }

        public override void OnLoad()
        {
            base.OnLoad();
            if (pressTestureName.Length > 0)
            {
                ResourceManager.ContentRoot = "Images";
                _pressTexture = ResourceManager.LoadTexture2D(pressTestureName);
            }
        }

        protected override void DrawSelf(SpriteBatch spriteBatch, Microsoft.Xna.Framework.GameTime gameTime)
        {
            spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.None, RasterizerState.CullCounterClockwise, null, Projection);
            spriteBatch.Draw(Texture, Position, null, this.Color, Rotation, Origin * new Vector2(Texture.Width, Texture.Height), Scale, SpriteEffects.None, 0);
            spriteBatch.End();
        }

        public bool Contain(Microsoft.Xna.Framework.Vector2 position)
        {
            position = Vector2.Transform(position, UnProjection);
            Vector2 topLeft = Position - Origin * new Vector2(_texture.Width, _texture.Height) * Scale;
            Vector2 rightDown = topLeft + new Vector2(_texture.Width, _texture.Height) * Scale;
            return (position.X > topLeft.X && position.X < rightDown.X && position.Y > topLeft.Y && position.Y < rightDown.Y);
        }

        public void OnTouch(TouchLocation touchLocation)
        {
            _pressed = true;
            if (OnTouchEvent != null)
                OnTouchEvent(this, touchLocation);
        }

        public void OnRelease(TouchLocation touchLocation)
        {
            _pressed = false;
            if (OnReleaseEvent != null)
                OnReleaseEvent(this, touchLocation);
        }

        public void OnHold(TouchLocation touchLocation)
        {
            if (OnHoldEvent != null)
                OnHoldEvent(this, touchLocation);
        }

    }
}
